import { defineStore } from 'pinia'
import { isLoggedIn as checkIsLoggedIn, getAccessToken, getUserId } from '@/utils/auth'
import { getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    studentInfo: {
      id: '',
      name: '',
      avatar: '',
      department: ''
    },
    isLoggedIn: false
  }),
  
  actions: {
    updateUserInfo(userInfo) {
      this.studentInfo = { ...this.studentInfo, ...userInfo }
      this.isLoggedIn = true
    },
    
    logout() {
      this.isLoggedIn = false
      this.studentInfo = {
        id: '',
        name: '',
        avatar: '',
        department: ''
      }
    },
    
    login() {
      this.isLoggedIn = true
    },
    
    // 检查用户登录状态
    checkLoginStatus() {
      this.isLoggedIn = checkIsLoggedIn()
      
      // 如果已登录，获取用户信息
      if (this.isLoggedIn) {
        this.fetchUserInfo()
      }
      
      return this.isLoggedIn
    },
    
    // 获取用户信息
    async fetchUserInfo() {
      try {
        const res = await getUserInfo()
        if (res.code === 0 && res.data) {
          // 更新用户信息
          this.updateUserInfo({
            id: res.data.id || getUserId(),
            name: res.data.nickname || '同学',
            avatar: res.data.avatar || 'https://randomuser.me/api/portraits/men/1.jpg',
            department: res.data.deptName || '计算机科学学院'
          })
        } else {
          // 如果获取失败，使用默认值
          this.updateUserInfo({
            id: getUserId(),
            name: '同学',
            avatar: 'https://randomuser.me/api/portraits/men/1.jpg',
            department: '计算机科学学院'
          })
        }
      } catch (error) {
        console.error('获取用户信息失败', error)
        // 如果获取失败，使用默认值
        this.updateUserInfo({
          id: getUserId(),
          name: '同学',
          avatar: 'https://randomuser.me/api/portraits/men/1.jpg',
          department: '计算机科学学院'
        })
      }
    },
    
    // 重置用户状态
    resetState() {
      this.isLoggedIn = false
      this.studentInfo = {
        id: '',
        name: '',
        avatar: '',
        department: ''
      }
    }
  }
})